<template>
  <div class="record-table">
    <table>
      <tr v-for="record in dataList" :key="record.record_id">
        <td>
          <div class="record-item black">
            <img
              :src="userAvatar(record.black_user_id.avatar)"
              alt="用户头像"
              class="user-avatar"
            />
            <span class="user-info">{{
              userInfo(record.black_user_id).username
            }}</span>
            <span class="date">{{ formatDate(record.end_time) }}</span>
            <span
              class="game-result"
              :class="{
                defeat: record.winner === 0,
                winner: record.winner === 1,
                tie: record.winner === 2,
              }"
              >{{
                record.winner === 2 ? "平局" : record.winner === 1 ? "胜" : "败"
              }}</span
            >
          </div>
          <span class="VS">VS</span>
          <div class="record-item white">
            <img
              :src="userAvatar(record.white_user_id.avatar)"
              alt="用户头像"
              class="user-avatar"
            />
            <span class="user-info">{{
              userInfo(record.white_user_id).username
            }}</span>
            <span class="date">{{ formatDate(record.end_time) }}</span>
            <span
              class="game-result"
              :class="{
                defeat: record.winner === 1,
                winner: record.winner === 0,
                tie: record.winner === 2,
              }"
              >{{
                record.winner === 2 ? "平局" : record.winner === 1 ? "败" : "胜"
              }}</span
            >
          </div>
        </td>
      </tr>
    </table>
    <div class="pagination">
      <button :disabled="currentPage === 1" @click="fetchData(currentPage - 1)">
        上一页
      </button>
      <span>第 {{ currentPage }} 页 / 共 {{ allPage }} 页</span>
      <button
        :disabled="currentPage === allPage"
        @click="fetchData(currentPage + 1)"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import useNetStore from "../../stores/net.js";
import { useUserStore } from "../../stores/user";
let userStore = useUserStore();
let net = useNetStore();
const recordTable = ref([]);
const userTable = ref([]);

// 获取对战记录列表
net
  .get("/users/recordTable")
  .then((res) => {
    if (res.code === 200) {
      recordTable.value = res.data;
      // console.log(recordTable.value)
      console.log(res.msg || "获取用户列表成功");
    } else {
      console.log(res.msg || "获取用户列表失败");
    }
  })
  .catch((err) => {
    console.error(err);
  });

// 获取用户列表
net
  .get("/users/userTable")
  .then((res) => {
    if (res.code === 200) {
      userTable.value = res.data;
      // console.log(userTable.value)
      console.log(res.msg || "获取用户列表成功");
    } else {
      console.log(res.msg || "获取用户列表失败");
    }
  })
  .catch((err) => {
    console.error(err);
  });
// 获取用户头像
function userAvatar(avatar) {
  return userStore.avatarUrl(avatar);
}
// 获取用户信息
function userInfo(id) {
  // console.log(userTable.value)
  // console.log(id)
  return (
    userTable.value.find((user) => user.userId == id) || {
      username: "未知用户",
      avatar: "",
    }
  );
}
// 格式化时间
function formatDate(date) {
  let formatTime = "";
  // 如果时间是今天就显示时间，否则显示日期
  // console.log(date);//2022-03-16T16:00:00.000Z
  // 转换为有效时间
  date = date.replace(/-/g, "/").replace("T", " ").replace(".000Z", "");
  // console.log(date);//2022-03-16 16:00:00
  const time = new Date(date);
  // console.log(time);
  const year = time.getFullYear();
  const month = time.getMonth() + 1;
  const day = time.getDate();
  const hour = time.getHours();
  const minute = time.getMinutes();
  const second = time.getSeconds();
  // console.log(year, month, day, hour, minute, second)
  // 如果是今天，显示时间，否则显示日期
  const now = new Date();
  const nowYear = now.getFullYear();
  const nowMonth = now.getMonth() + 1;
  const nowDay = now.getDate();
  if (year === nowYear && month === nowMonth && day === nowDay) {
    // 今天
    formatTime = hour + ":" + minute + ":" + second;
  } else {
    // 昨天以前
    const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
    const yesterdayYear = yesterday.getFullYear();
    const yesterdayMonth = yesterday.getMonth() + 1;
    const yesterdayDay = yesterday.getDate();
    if (
      year === yesterdayYear &&
      month === yesterdayMonth &&
      day === yesterdayDay
    ) {
      // 昨天
      formatTime = "昨天 " + hour + ":" + minute + ":" + second;
    } else {
      // 之前
      formatTime = year + "/" + month + "/" + day;
    }
  }
  return formatTime;
}

const currentPage = ref(1); // 当前页码
const dataList = ref([]); // 当前页数据
const pageSize = ref(10); // 每页条数
let allPage = ref(0); // 总页数
let total = ref(0); // 总数据条数
onMounted(() => {
  setTimeout(() => {
    total.value = ref(recordTable.value.length); // 总数据条数
    allPage.value = Math.ceil(total.value / pageSize.value); // 总页数
    fetchData(1);
  }, 100);
});
// 分页
function fetchData(page = 1) {
  const start = (page - 1) * pageSize.value;
  const end = start + pageSize.value;
  dataList.value = recordTable.value.slice(start, end);
  total.value = recordTable.value.length;
  currentPage.value = page;
  allPage.value = Math.ceil(total.value / pageSize.value);
  const container = document.querySelector(".record-table");
  if (container) {
    container.scrollTop = 0;
  }
}
</script>

<style scoped>
.record-table {
  width: 100%;
  margin: 0px auto;
  background: #f4f8fb;
  border-radius: 18px;
  box-shadow: 0 4px 24px rgba(60, 60, 60, 0.08);
  overflow: auto;
  height: 80vh;
  scrollbar-width: thin;
}

table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 22px;
}

tr {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 10px rgba(60, 60, 60, 0.06);
  transition: box-shadow 0.2s;
}

tr:hover {
  box-shadow: 0 4px 20px rgba(60, 60, 60, 0.12);
}

td {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 使左右两侧内容靠左右对齐 */
  padding: 22px 28px;
  border: none;
}

.record-item {
  flex: 1; /* 确保左右两侧的内容均分剩余空间 */
  text-align: center;
  display: inline-flex;
  align-items: center;
  min-width: 260px;
}

.user-avatar {
  width: 54px;
  height: 54px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 16px;
  border: 3px solid #3b82f6;
  background: #e0e7ff;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
  transition: border 0.2s;
}

.user-info {
  font-weight: 700;
  color: #2563eb;
  margin-right: 16px;
  font-size: 1.18rem;
  letter-spacing: 1px;
}

.date {
  color: #64748b;
  font-size: 1rem;
  margin-right: 16px;
}

.game-result {
  font-size: 1.08rem;
  font-weight: 700;
  margin-right: 8px;
  padding: 2px 12px;
  border-radius: 8px;
  background: #f0fdfa;
  color: #10b981;
  border: 1.5px solid #34d399;
  letter-spacing: 1px;
}

.defeat {
  color: #ef4444;
  background: #fef2f2;
  border-color: #fca5a5;
}

.winner {
  color: #3b82f6;
  background: #eff6ff;
  border-color: #93c5fd;
}

.tie {
  color: #10b981;
  background: #f0fdfa;
  border-color: #34d399;
}

span.VS {
  font-weight: bold;
  color: #fb923c;
  margin: 0 32px;
  font-size: 1.5rem;
  letter-spacing: 2px;
  vertical-align: middle;
  display: inline-block;
  background: #fff7ed;
  padding: 4px 18px;
  border-radius: 10px;
  box-shadow: 0 1px 4px rgba(251, 146, 60, 0.08);
}

/* 左侧的胜败右对齐 */
.record-item.black .game-result {
  margin-left: auto; /* 自动调整为右对齐 */
  margin-right: 0; /* 清除默认的右间距 */
}

/* 右侧的胜败左对齐 */
.record-item.white .game-result {
  margin-left: 0; /* 清除默认的左间距 */
  margin-right: auto; /* 自动调整为左对齐 */
}

.record-item.white {
  flex-direction: row-reverse; /* 右侧内容反向排列 */
}

@media (max-width: 700px) {
  .record-table {
    padding: 8px 0;
  }
  td {
    padding: 12px 4px;
  }
  .record-item {
    min-width: 120px;
  }
  span.VS {
    margin: 0 8px;
    font-size: 1.1rem;
    padding: 2px 8px;
  }
  .user-avatar {
    width: 36px;
    height: 36px;
    margin-right: 8px;
  }
}
</style>
